#coding=utf-8

from func_ext import md5
import pymongo
import memcache_proxy
import AloneDB

class core(object) :
    """""""""""""""""""""""""""""""""""""""""""""
     # 核心调用库
     # @class
     # @copyright Copyright (c) 2010, pe-dev. inc
     # @author alone <phperlon@gmail.com>
     # @license
    """""""""""""""""""""""""""""""""""""""""""""
    singleton_instance = {} #普通单例对象
    db_singleton_instance = {} #数据库单例对象
    mongo_singleton_instance = {} #mongo单例对象
    memcache_singleton_instance = {} #memcache单例对象

    def __init__(self) :
        self.setting = globals().get('setting',{})
        if not self.setting :
            from config import config
            self.setting = config().setting()

    def database(self,dbKey='db') :
        """""""""""""""""""""""""""""""""""""""
         # 获取数据库连接单例对象
         #
         # @author   alone <phperlon@gmail.com>
         # @param    string dbKey mysql配置项key
         # @return   object
         # @todo     
        """""""""""""""""""""""""""""""""""""""
        key = md5('__DATABASE__'+dbKey)
        if not self.db_singleton_instance.get(key) :
            self.db_singleton_instance[key] = AloneDB.database(self.setting,dbKey)
        return self.db_singleton_instance[key]

    def memcache(self,cacheKey,memKey='memcache') :
        """""""""""""""""""""""""""""""""""""""
         # 获取memcache单例对象
         #
         # @author   alone <phperlon@gmail.com>
         # @param    string cacheKey memcache配置项option Key
         # @param    string memKey memcache配置项key
         # @return   object
         # @todo     
        """""""""""""""""""""""""""""""""""""""
        key = md5('__MEMCACHE__'+cacheKey)
        if not self.memcache_singleton_instance.get(key) :
            #获取memcache 连接地址
            memOption = self.setting.get(memKey).get(cacheKey)
            self.memcache_singleton_instance[key] = memcache_proxy.Client(memOption)
        return self.memcache_singleton_instance[key]

    def mongo(self,mongoKey='mongodb') :
        """""""""""""""""""""""""""""""""""""""
         # 获取mongo单例对象
         #
         # @author   alone <phperlon@gmail.com>
         # @param    string mongoKey mongo配置项key
         # @return   object
         # @todo     
        """""""""""""""""""""""""""""""""""""""
        key = md5('__MONGO__'+mongoKey)
        if not self.mongo_singleton_instance.get(key) :
            mongoConf = self.setting.get(mongoKey,{})
            if not mongoConf :
                self.mongo_singleton_instance[key] = pymongo.Connection()
            else :
                mongoHost = mongoConf.get('mongo_host')
                mongoPort = int(mongoConf.get('mongo_port',27017))
                self.mongo_singleton_instance[key] = pymongo.Connection(host=mongoHost,port=mongoPort)
        return self.mongo_singleton_instance[key]
